package com.karaoke.android.newok

import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import com.apkfuns.logutils.LogUtils
import com.esafirm.rxdownloader.RxDownloader
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog
import com.github.javiersantos.materialstyleddialogs.enums.Style
import com.github.pwittchen.reactivenetwork.library.Connectivity
import com.github.pwittchen.reactivenetwork.library.ReactiveNetwork
import com.karaoke.android.data.NetworkTools
import com.karaoke.android.data.domain.*
import com.karaoke.android.data.krealmextensions.createOrUpdate
import com.karaoke.android.data.krealmextensions.queryFirst
import com.karaoke.android.data.krealmextensions.save
import com.karaoke.android.data.onIO
import com.karaoke.android.data.onUI
import com.karaoke.android.data.utils.getDeviceSN
import com.karaoke.android.data.utils.hideSystemBar
import com.karaoke.android.data.websocket.WebSocketClient
import com.karaoke.android.library.mvvm.AbstractActivity
import com.karaoke.android.library.utils.SilentInstall
import com.orhanobut.hawk.Hawk
import com.stericson.RootShell.RootShell
import com.stericson.RootShell.execution.Command
import com.stericson.RootShell.execution.Shell
import com.stericson.RootTools.RootTools
import com.trello.rxlifecycle.kotlin.bindToLifecycle
import io.realm.Realm
import io.realm.RealmConfiguration
import org.acra.ACRA
import org.simple.eventbus.EventBus
import org.simple.eventbus.Subscriber
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import tv.danmaku.ijk.media.player.misc.ITrackInfo
import java.io.*
import java.net.URI
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit

class MainActivity : AbstractActivity()
{

    private var reCount = 0

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        hideSystemBar(true)
        setContentView(R.layout.activity_main)
        EventBus.getDefault().register(this)
        if (!getDeviceSN().isNullOrEmpty())
            NetworkTools.webSocketClient.onConnect()
        else
        {
            MaterialStyledDialog.Builder(this)
                    .setTitle("错误")
                    .setDescription("设备唯一ID不合法，请联系商家")
                    .setStyle(Style.HEADER_WITH_ICON)
                    .setIcon(R.drawable.ic_waning)
                    .setCancelable(false)
                    .show()
        }
    }


    @Subscriber
    fun onSocketOpened(e: WebSocketClient.StateChanged)
    {
        when (e.state)
        {
            WebSocketClient.State.Opened  ->
            {
//                NetworkTools.webSocketClient.sendMessage(Message<String>(Command.PublicSongs))
//                NetworkTools.webSocketClient.sendMessage(Message<String>(Command.ScrollTexts))
            }
            WebSocketClient.State.Closed  ->
            {
            }
            WebSocketClient.State.Closing ->
            {
            }
            WebSocketClient.State.Failure ->
            {
                if (reCount < 5)
                {
                    Observable.timer(2, TimeUnit.SECONDS).subscribe {
                        LogUtils.e("重连 socket")
                        reCount++
                        NetworkTools.webSocketClient.onConnect()
                    }
                }
                else
                {
                    MaterialStyledDialog.Builder(this)
                            .setTitle("错误")
                            .setDescription("连接服务器失败！")
                            .setStyle(Style.HEADER_WITH_ICON)
                            .setIcon(R.drawable.ic_waning)
                            .setPositiveText("重试")
                            .setNegativeText("系统设置")
                            .setCancelable(false)
                            .onPositive { _, _ ->
                                reCount = 0
                                NetworkTools.webSocketClient.onConnect()
                            }
                            .onNegative { _, _ ->
                                hideSystemBar(false)
                                val intent = Intent(Settings.ACTION_SETTINGS)
                                startActivity(intent)
                            }
                            .show()
                }
            }
        }
    }

    @Subscriber
    fun onReceiveRoomInfo(info: DeviceData)
    {
        if (info.room == null)
        {
            MaterialStyledDialog.Builder(this)
                    .setTitle("错误")
                    .setDescription("设备未注册")
                    .setStyle(Style.HEADER_WITH_ICON)
                    .setIcon(R.drawable.ic_waning)
                    .setPositiveText("重试")
                    .setNegativeText("系统设置")
                    .setCancelable(false)
                    .onPositive { _, _ ->
                        //getRoomInfo()
                        NetworkTools.webSocketClient.onClose()
                        NetworkTools.webSocketClient.onConnect()
                    }
                    .onNegative { _, _ ->
                        hideSystemBar(false)
                        val intent = Intent(Settings.ACTION_SETTINGS)
                        startActivity(intent)
                    }
                    .show()
        }
        else
        {
            val local = DeviceData().queryFirst()
            local?.let {
                if (info.dbVersion != local.dbVersion)
                {
                    Realm.getDefaultInstance().executeTransaction(Realm::deleteAll)
                    Hawk.deleteAll()
                }
            }
            info.save()
            ACRA.getErrorReporter().putCustomData("uuid", getDeviceSN())
            ACRA.getErrorReporter().putCustomData("roomNo", info.room?.no)
            NetworkTools.udpClient.onConnect()
            Observable.just("s").delay(1, TimeUnit.SECONDS).subscribe({ mount(info.filePaths); }, {})
            startHome()
        }
    }


    override fun onStop()
    {
        super.onStop()
    }

    private fun startHome()
    {
        val intent = Intent()
        intent.setClassName(this, "com.karaoke.android.home.HomeActivity")
        intent.addCategory(Intent.CATEGORY_HOME)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
        finish()
    }


    override fun onDestroy()
    {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    fun mount(filePaths: List<FilePath>)
    {
        if (RootTools.isAccessGiven())
            filePaths.forEach { filePath ->
                val dir = File(Environment.getExternalStorageDirectory(), "/" + filePath.dirName)
                if (!dir.exists()) dir.mkdirs()
                val shell = RootTools.getShell(true, Shell.ShellContext.SYSTEM_APP)
                val path = filePath.path.replace("\\", "/")
                val cmd = object : Command(
                        0,
                        "busybox mount -t cifs -o username=administrator,password=Goodktv..,iocharset=utf8 $path ${dir.absolutePath}")
                {
                    override fun commandOutput(id: Int, line: String?)
                    {
                        super.commandOutput(id, line)
                        LogUtils.e(line)
                    }

                    override fun commandCompleted(id: Int, exitcode: Int)
                    {
                        super.commandCompleted(id, exitcode)
                        shell.close()
                    }
                }
                shell.add(cmd)
            }
    }
}
